#include "process_pool.h"

int main(int argc,char *argv[])
{
    if(argc!=4)
    {
        printf("usage:%s ip port processnum\n",argv[0]);
    }
    int ret;
    int processNum=atoi(argv[3]);
    int i,j;
    process_data_t *pData=(process_data_t*)calloc(processNum,sizeof(process_data_t));
    make_child(pData,processNum);
    int sockfd;
    tcp_init(&sockfd,argv[1],argv[2]);
    struct sockaddr_in cli;
    int newfd;
    //新建一个epoll实例
    int epfd=epoll_create(1);
    struct epoll_event event,*evs;
    evs=(struct epoll_event*)calloc(processNum+1,sizeof(struct epoll_event));
    event.data.fd=sockfd;
    event.events=EPOLLIN;
    ret=epoll_ctl(epfd,EPOLL_CTL_ADD,sockfd,&event);
    ERROR_CHECK(ret,-1,"epoll_ctl");
    for(i=0;i<processNum;++i)
    {
        event.data.fd=pData[i].fd;
        epoll_ctl(epfd,EPOLL_CTL_ADD,pData[i].fd,&event);
    }
    int readyNum;
    char doneFlag=0;
    while(1)
    {
        readyNum=epoll_wait(epfd,evs,processNum+1,-1);
        for(i=0;i<readyNum;++i)
        {
            if(evs[i].data.fd==sockfd)
            {

                bzero(&cli,sizeof(cli));
                socklen_t len=sizeof(cli);
                newfd=accept(sockfd,(struct sockaddr*)&cli,&len);
                ERROR_CHECK(newfd,-1,"accept");
                printf("client ip=%s,client port=%d\n",
                       inet_ntoa(cli.sin_addr),ntohs(cli.sin_port));
                //找到不忙碌的子进程并把任务分配给它
                for(j=0;j<processNum;++j)
                {
                    if(0==pData[j].busy)
                    {
                        sendfd(pData[j].fd,newfd);
                        //write(pData[i].fd,&newfd,sizeof(int));
                        printf("Give assignment %d to %d\n",newfd,pData[j].pid);
                        pData[i].busy=1;
                        //父进程及时关闭文件描述符
                        close(newfd);
                        break;
                    }
                }
                continue;//直接继续外层循环
            }
            //子进程空闲通知父进程
            for(j=0;j<processNum;++j)
            {
                if(evs[i].data.fd==pData[j].fd)
                {
                    read(evs[i].data.fd,&doneFlag,sizeof(doneFlag));
                    pData[j].busy=0;
                    printf("%d now is not busy,get tag %c\n",pData[j].pid,doneFlag);
                    break;
                }
            }
        }
    }
    return 0;
}

